package com.adnaan.backend.common.interceptor;


import com.adnaan.backend.common.exception.BizException;
import com.adnaan.backend.entity.SysUser;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author: adnaan
 * create: 2023-11-29 14:28
 * Description: 登录拦截
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从redis当中取当前用户，取到的话说明请求是已登录用户的请求
        String requestUrl = request.getRequestURI();
        String[] whiteList = new String[]{
                "/api/user",
                "/api/sys_role",
                "/api/device",
                "/api/site",
                "/api/alert_log",
                "/api/alert_setting",
                "/api/tw_record"
        };
        System.out.println("拦截器进行拦截");
        String token = request.getHeader("Authorization");
        System.out.println("token:" + token);
        if (token == null) {
            throw new BizException(401, "认证失败，非法用户");
        }
        boolean hasUrl = false;
        for (String url : whiteList) {
            if (requestUrl.startsWith(url)) {
                hasUrl = true;
                break;
            }
        }
        if (hasUrl&&token.startsWith("user")) {
            throw new BizException(401, "认证失败，非法用户");
        }else if (!hasUrl &&token.startsWith("admin")) {
            throw new BizException(401, "认证失败，非法用户");
        }
        String userJson = stringRedisTemplate.opsForValue().get(token);
        System.out.println(userJson);
        if (token.startsWith("admin") && userJson == null) {
            throw new BizException(402, "管理员token过期");
        } else if(token.startsWith("user") && userJson == null){
            throw new BizException(403, "用户token过期");
        }
        System.out.println("通过");
        SysUser curUser = JSON.parseObject(userJson, SysUser.class);
        if (curUser != null) {
            request.setAttribute("userId", curUser.getId());
        }
        return true;
    }
}
